package com.roncoo.education.course.feign.biz;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.roncoo.education.common.core.tools.BeanUtil;
import com.roncoo.education.common.service.BaseBiz;
import com.roncoo.education.course.dao.ExperimentDao;
import com.roncoo.education.course.dao.ExperimentScoreDao;
import com.roncoo.education.course.dao.ExperimentScoreReportDao;
import com.roncoo.education.course.dao.ExperimentScoreStepDao;
import com.roncoo.education.course.dao.ZoneDao;
import com.roncoo.education.course.dao.impl.mapper.entity.ExperimentScore;
import com.roncoo.education.course.dao.impl.mapper.entity.ExperimentScoreExample;
import com.roncoo.education.course.dao.impl.mapper.entity.ExperimentScoreReport;
import com.roncoo.education.course.dao.impl.mapper.entity.ExperimentScoreReportExample;
import com.roncoo.education.course.dao.impl.mapper.entity.ExperimentScoreStep;
import com.roncoo.education.course.feign.interfaces.score.CallbackExperimentScoreReportReq;
import com.roncoo.education.course.feign.interfaces.score.CallbackExperimentScoreReq;
import com.roncoo.education.course.feign.interfaces.score.CallbackExperimentScoreStepReq;
import com.roncoo.education.course.feign.interfaces.score.UploadResp;
import com.roncoo.education.course.feign.interfaces.score.constant.UploadAttachmentCodeConst;
import com.roncoo.education.course.feign.interfaces.score.constant.UploadScoreCodeConst;
import com.roncoo.education.user.feign.interfaces.IFeignUsers;
import com.roncoo.education.user.feign.interfaces.vo.UsersVO;

import lombok.RequiredArgsConstructor;

/**
 * ADMIN-实验分数
 *
 * @author wujing
 */
@Component
@RequiredArgsConstructor
public class FeignExperimentScoreBiz extends BaseBiz {

    @NotNull
    private final ExperimentScoreDao dao;
    @NotNull
    private final ExperimentScoreStepDao stepDao;
    @NotNull
    private final ExperimentScoreReportDao reportDao;
    @NotNull
    private final ZoneDao zoneDao;
    @NotNull
    private final ExperimentDao experimentDao;
    @NotNull
    private final IFeignUsers feignUsers;

    /**
     * 实验分数添加
     *
     * @param req 实验分数
     * @return 添加结果
     * @throws UploadResp 
     */
    public UploadResp uploadScore(CallbackExperimentScoreReq req) {
    	String userid = req.getUsername();
    	if (StringUtil.isBlank(userid)) {    		
    		return new UploadResp(UploadScoreCodeConst.code_19, UploadScoreCodeConst.code_19_msg);
    	}
    	
    	UsersVO user = null;
    	try {
    		user = feignUsers.getById(Long.parseLong(userid));	
    	} catch (Exception e) {
    		return new UploadResp(UploadScoreCodeConst.code_19, UploadScoreCodeConst.code_19_msg);
    	}
    	
    	if (user == null) {
    		return new UploadResp(UploadScoreCodeConst.code_19, UploadScoreCodeConst.code_19_msg);
    	}
    	
    	Long appid = Long.parseLong(req.getAppid());
    	if (experimentDao.getById(appid) == null) {
			return new UploadResp(UploadScoreCodeConst.code_12, UploadScoreCodeConst.code_12_msg);
    	}
    	
    	ExperimentScoreExample example = new ExperimentScoreExample();
    	example.createCriteria().andOriginIdEqualTo(req.getOriginId()).andAppidEqualTo(req.getAppid());
    	if (dao.countByExample(example) >= 1) {
    		return new UploadResp(UploadScoreCodeConst.code_15, UploadScoreCodeConst.code_15_msg);
    	}
    	
        ExperimentScore record = BeanUtil.copyProperties(req, ExperimentScore.class);
        LocalDateTime startTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(req.getStartTime()), ZoneId.systemDefault());
        LocalDateTime endTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(req.getEndTime()), ZoneId.systemDefault());
        record.setStartTime(startTime);
        record.setEndTime(endTime);
        record.setGroupId(req.getGroup_id());
        record.setGroupName(req.getGroup_name());
        record.setRoleInGroup(req.getRole_in_group());
        record.setGroupMembers(req.getGroup_members());
        record.setMobile(user.getMobile());
        ArrayList<CallbackExperimentScoreStepReq> steps = req.getSteps();
        if (steps == null || steps.size() == 0) {
//        	return Result.error("缺失操作步骤");
        	return new UploadResp(UploadScoreCodeConst.code_6, UploadScoreCodeConst.code_6_msg);
        }
        ArrayList<ExperimentScoreStep> steps2 = new ArrayList<ExperimentScoreStep>();
        
        for (CallbackExperimentScoreStepReq stepReq : steps) {
        	ExperimentScoreStep step = BeanUtil.copyProperties(stepReq, ExperimentScoreStep.class);
            LocalDateTime startTime2 = LocalDateTime.ofInstant(Instant.ofEpochMilli(stepReq.getStartTime()), ZoneId.systemDefault());
            LocalDateTime endTime2 = LocalDateTime.ofInstant(Instant.ofEpochMilli(stepReq.getEndTime()), ZoneId.systemDefault());
            step.setStartTime(startTime2);
            step.setEndTime(endTime2);
            step.setExtData(stepReq.getExt_data());
            steps2.add(step);
		}
        
        if (dao.save(record) > 0) {
        	for (ExperimentScoreStep step : steps2) {
        		step.setExperimentScoreId(record.getId());
        		stepDao.save(step);
        	}
        	
        	return new UploadResp(UploadScoreCodeConst.code_0, record.getId().toString());
        }

        return new UploadResp(UploadScoreCodeConst.code_999, UploadScoreCodeConst.code_999_msg);
    }
    
    public UploadResp uploadAttachment(CallbackExperimentScoreReportReq req, MultipartFile file) {    	
    	if (StringUtil.isBlank(req.getContents())) {
    		return new UploadResp(UploadAttachmentCodeConst.code_8, UploadAttachmentCodeConst.code_8_msg);
    	}
    	
    	if (req.getContents().getBytes().length > 1024 * 1024 * UploadAttachmentCodeConst.contentSize) {
    		return new UploadResp(UploadAttachmentCodeConst.code_8, UploadAttachmentCodeConst.code_8_msg);
    	}
    	
    	Long appid = Long.parseLong(req.getAppid());
    	if (experimentDao.getById(appid) == null) {
    		return new UploadResp(UploadAttachmentCodeConst.code_4, UploadAttachmentCodeConst.code_4_msg);
    	}
    	
    	ExperimentScoreExample example = new ExperimentScoreExample();
    	example.createCriteria().andAppidEqualTo(req.getAppid()).andOriginIdEqualTo(req.getOriginId());

    	List<ExperimentScore> list = dao.listByExample(example);
    	if (list == null || list.size() == 0) {
    		return new UploadResp(UploadAttachmentCodeConst.code_7, UploadAttachmentCodeConst.code_7_msg);
    	}
    	
    	if (list.size() > 1) {
    		return new UploadResp(UploadAttachmentCodeConst.code_11, UploadAttachmentCodeConst.code_11_msg);    		
    	}

    	ExperimentScoreReportExample example2 = new ExperimentScoreReportExample();
    	example2.createCriteria().andOriginIdEqualTo(req.getOriginId());
    	if (reportDao.countByExample(example2) >= 1) {
    		return new UploadResp(UploadAttachmentCodeConst.code_6, UploadAttachmentCodeConst.code_6_msg);
    	}
    	    	    
        ExperimentScoreReport record = BeanUtil.copyProperties(req, ExperimentScoreReport.class);
        record.setExperimentScoreId(list.get(0).getId());
        if (reportDao.save(record) > 0) {
            return new UploadResp(UploadAttachmentCodeConst.code_0, record.getId().toString());
        }
        return new UploadResp(UploadAttachmentCodeConst.code_999, UploadAttachmentCodeConst.code_999_msg);
    }    
}
